//
//  MoviePlayerViewController.m
//  ITHome
//
//  Created by lanou3g on 15/7/14.
//  Copyright (c) 2015年 YAX. All rights reserved.
//

#import "MoviePlayerViewController.h"
@interface MoviePlayerViewController ()
@end

@implementation MoviePlayerViewController

- (void)viewDidAppear:(BOOL)animated
{
    self.moviePlayer.fullscreen = YES;
}

- (void)viewDidLoad {
    self.view.backgroundColor = [UIColor whiteColor];
    [super viewDidLoad];
    //创建播放器
    [self initMoviePlay];
    //播放视屏
    [self.moviePlayer play];
    //添加监听
    [self addNotification];
    
}

- (void)initMoviePlay
{
     NSURL *url = [NSURL URLWithString:_mp4_url];
    //创建播放器。
    self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
    //播放器类型 嵌入式：解决上下一曲黑屏问题。
    self.moviePlayer.controlStyle = MPMovieControlStyleEmbedded;
    //自适应宽高
    self.moviePlayer.view.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:_moviePlayer.view];
    self.moviePlayer.view.frame = self.view.bounds;
    self.moviePlayer.controlStyle = MPMovieControlStyleFullscreen;
}

- (void)addNotification
{
    //1.监听播放状态。
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stateChanged) name:MPMoviePlayerPlaybackStateDidChangeNotification object:nil];
    //2.监听播放完成.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finished) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
    //3.监听全屏。
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finished) name:MPMoviePlayerDidExitFullscreenNotification object:nil];
}

- (void)stateChanged
{
    switch (self.moviePlayer.playbackState) {
        case MPMoviePlaybackStatePlaying:
            NSLog(@"播放");
            break;
        case MPMoviePlaybackStatePaused:
            NSLog(@"暂停");
            break;
        case MPMoviePlaybackStateStopped:
            NSLog(@"停止");
            break;
        default:
            break;
    }
    
}

- (void)finished
{
    //删除通知监听。
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    //谁申请 谁释放(问题：第一次dismiss 是从控制器 -> 本控制器 第二次dismiss 是本控制器 -> 前控制器)
    [self dismissViewControllerAnimated:NO completion:nil];
    [self dismissViewControllerAnimated:YES completion:nil];

    
    NSLog(@"完成");
}
@end
